﻿/*
	Copyright (c) 2013 Andrew Meyer

	Permission is hereby granted, free of charge, to any person obtaining a copy of this software
	and associated documentation files (the "Software"), to deal in the Software without
	restriction, including without limitation the right to use, copy, modify, merge, publish,
	distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the
	Software is furnished to do so, subject to the following conditions:

	The above copyright notice and this permission notice shall be included in all copies or
	substantial portions of the Software.

	THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING
	BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
	NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
	DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
	OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*/

using System;
using System.Collections.Generic;
using System.Linq;
using System.Windows.Input;
using Ascend;

namespace AscendViewer
{
	public class AnimatedContentNodeViewModel : ModelContentNodeViewModel
	{
		#region Lifecycle
		public AnimatedContentNodeViewModel(AnimatedSceneNode animatedSceneNode,
			Queue<TransformableObject> axisSceneAliases,
			Queue<TransformableObject> boneSceneAliases, ContentExplorerViewModel container,
			ContentNodeViewModel parent)
			: base(animatedSceneNode, axisSceneAliases, boneSceneAliases, container, parent)
		{
			_timelines = new Dictionary<string, Timeline>();
			Animations = new List<string>(animatedSceneNode.ListAnimations());
			SetupTimelines();

			if (HasAnimations)
			{
				AnimationIndex = 0;
			}

			if (animatedSceneNode.Armature != null)
			{
				Children.Insert(0, Create(animatedSceneNode.Armature, axisSceneAliases,
					boneSceneAliases, container, this));
			}
			
			PreviousAnimationCommand = new InterfaceCommand(
				() =>
				{
					AnimationIndex--;
				},
				() => Animations.Count > 1 && IsPaused);

			NextAnimationCommand = new InterfaceCommand(
				() =>
				{
					AnimationIndex++;
				},
				() => Animations.Count > 1 && IsPaused);

			FrameRateUpCommand = new InterfaceCommand(() => FrameRate += 5, () => IsPaused);
			FrameRateDownCommand = new InterfaceCommand(() => FrameRate -= 5, () => IsPaused);
		}
		#endregion

		#region Private Members
		private Dictionary<string, Timeline> _timelines;
		private string _lastPlayedAnimation;
		#endregion

		#region Public Properties
		public ICommand PreviousAnimationCommand
		{
			get;
			private set;
		}

		public ICommand NextAnimationCommand
		{
			get;
			private set;
		}

		public ICommand FrameRateUpCommand
		{
			get;
			private set;
		}

		public ICommand FrameRateDownCommand
		{
			get;
			private set;
		}

		public List<string> Animations
		{
			get;
			private set;
		}

		public bool HasAnimations
		{
			get
			{
				return Animations.Any();
			}
		}

		private int _animationIndex = -1;
		public int AnimationIndex
		{
			get
			{
				return _animationIndex;
			}

			set
			{
				if (_animationIndex == value)
				{
					return;
				}

				_animationIndex = value;

				// Wrap-around
				if (_animationIndex < 0)
				{
					_animationIndex = Animations.Count + _animationIndex;
				}
				else if (_animationIndex >= Animations.Count)
				{
					_animationIndex = Animations.Count - _animationIndex;
				}

				CurrentAnimation = Animations[_animationIndex];
			}
		}

		private string _currentAnimation;
		public string CurrentAnimation
		{
			get
			{
				return _currentAnimation;
			}

			set
			{
				if (_currentAnimation == value)
				{
					return;
				}

				_currentAnimation = value;
				NotifyPropertyChanged("CurrentAnimation");
			}
		}

		private double _frameRate = 60.0;
		public double FrameRate
		{
			get
			{
				return _frameRate;
			}

			set
			{
				if (value == 0.0)
				{
					throw new ArgumentException("Invalid frame rate");
				}

				if (_frameRate == value)
				{
					return;
				}

				_frameRate = value;
				NotifyPropertyChanged("FrameRate");
			}
		}

		private bool _isPlaying;
		public bool IsPlaying
		{
			get
			{
				return _isPlaying;
			}

			set
			{
				if (_isPlaying == value || Data == null)
				{
					return;
				}

				_isPlaying = value;

				if (_isPlaying)
				{
					Play();
				}
				else
				{
					Pause();
				}

				NotifyPropertyChanged("IsPlaying");
				NotifyPropertyChanged("IsPaused");
			}
		}

		public bool IsPaused
		{
			get
			{
				return !IsPlaying;
			}
		}
		#endregion

		#region Private Methods
		private void SetupTimelines()
		{
			// Create separate timeline for each animation
			foreach (string anim in Animations)
			{
				Timeline timeline = new Timeline();

				timeline.Animations.Add(new TimelineAnimation((AnimatedSceneNode)Data, anim));
				timeline.Animations.Add(new TimelineAnimation((AnimatedSceneNode)_axisSceneAlias, anim));
				timeline.Animations.Add(new TimelineAnimation((AnimatedSceneNode)_boneSceneAlias, anim));

				_timelines.Add(anim, timeline);
			}
		}

		private void Play()
		{
			// Restart if changed to new animation
			bool restart = CurrentAnimation != _lastPlayedAnimation;

			_timelines[CurrentAnimation].Play(true, restart, FrameRate);
			_lastPlayedAnimation = CurrentAnimation;
		}

		private void Pause()
		{
			_timelines[CurrentAnimation].Pause();
		}
		#endregion
	}
}
